#include "TimeController.h"
#include "Utils.h"

#ifdef ANDROID
#include <unistd.h>
#endif

TimeController::TimeController()
{
	SetFPSExpect(DEFAULT_FPS);
	dt = 0;
	startTime = -1;
}

TimeController* TimeController::GetInstance()
{
	if(instance == 0)
	{
		PRINT("Init TimeController\n");
		instance = new TimeController();
	}
	return instance;
}

float TimeController::GetTimeNow()
{
	return (float)clock()/CLOCKS_PER_SEC*1000;
}

void TimeController::Start()
{
	startTime = endTime = GetTimeNow();
}

void TimeController::Limit()
{
	endTime = GetTimeNow();
	if(startTime == -1) startTime = endTime;

	float dtThisFrame = endTime - startTime;
	if(dtThisFrame < dtExpect)
	{
		dt = dtExpect;
		SleepNow(dtExpect-dtThisFrame);
	}
	else{
		dt = dtThisFrame;
		SleepNow(1);
	}
	startTime = GetTimeNow();

	if(dt>1000)
		dt = 0;			//prevent return too big value when debug

}

void TimeController::SleepNow(int milisecond)
{
#ifdef WIN32
	Sleep(milisecond);
#else
	usleep(milisecond*1000);
#endif
}

float TimeController::GetDtInSecond()
{
	return dt/1000;
}

void TimeController::SetFPSExpect(int FPSExpect)
{
	this->FPSExpect = FPSExpect;
	this->dtExpect = 1000.0f/FPSExpect;
}


void TimeController::Destroy()
{
	PRINT("Destroy TimeController\n");
	DELETE_SAFELY(instance);
}

TimeController::~TimeController(){}

TimeController* TimeController::instance = NULL;